package com.gx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gx.domain.oss.*;
import com.gx.service.api.OssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;

//@Service
public class OssImpl implements OssService {

    private static final Logger logger = LoggerFactory.getLogger(OssImpl.class);

    @Value("${oss.bucket.name}") private String OSS_BUCKET_NAME;
    @Value("${oss.end.point}") private String OSS_END_POINT;
    @Value("${oss.access.key.id}") private String OSS_ACCESS_KEY_ID;
    @Value("${oss.access.key.secret}") private String OSS_ACCESS_KEY_SECRET;

    @Value("${oss.sts.bucket.name}") private String STS_BUCKET_NAME;
    @Value("${oss.sts.end.point}") private String STS_END_POINT;
    @Value("${oss.sts.access.key.id}") private String STS_ACCESS_KEY_ID;
    @Value("${oss.sts.access.key.secret}") private String STS_ACCESS_KEY_SECRET;
    @Value("${oss.sts.role.arn}") private String STS_ROLE_ARN;
    @Value("${oss.sts.out.time}") private long STS_OUT_TIME;
    @Value("${oss.out.time}") private Integer OSS_OUT_TIME;

    /**
     * OSS生成临时授权
     * @param AuthOssStsRequest
     * @return AuthOssStsResponse
     * @date 2018-10-25 11:53:00
     */
    @Override
    public BaseResponse<AuthOssStsResponse> authOssSts(CommonParam commonParam, AuthOssStsRequest request) {
        BaseResponse<AuthOssStsResponse> res = new BaseResponse();
        AuthOssStsResponse data = new AuthOssStsResponse();

        String bucket = STS_BUCKET_NAME;
        String endpoint=STS_END_POINT;
        String accessKeyId=STS_ACCESS_KEY_ID;
        String accessKeySecret=STS_ACCESS_KEY_SECRET;
        // 扮演角色
        String RoleArn=STS_ROLE_ARN;
        // 超时时间
        long outTime=STS_OUT_TIME;

        try {

            String resource = bucket + "/";
            if (request.getBucket() != null && !"".equals(request.getBucket())) {
                resource = request.getBucket() + "/";
            }
            if (request.getPath() != null && !"".equals(request.getPath())) {
                resource += request.getPath() + "/";
            }
            if (request.getFileName() != null && !"".equals(request.getFileName())) {
                resource += request.getFileName();
            } else {
                resource += "*";
            }
            if (request.getOutTime() != null && request.getOutTime() > 0) {
                outTime = request.getOutTime();
            }

            String policy = "{\n" +
                    "    \"Version\": \"1\", \n" +
                    "    \"Statement\": [\n" +
                    "        {\n" +
                    "            \"Action\": [\n" +
                    "                \"oss:*\"\n" +
                    "            ], \n" +
                    "            \"Resource\": [\n" +
                    "                \"acs:oss:*:*:" + resource + "\" \n" +
                    "            ], \n" +
                    "            \"Effect\": \"Allow\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";

            DefaultProfile.addEndpoint("", "", "Sts", endpoint);
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);

            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest();
            assumeRoleRequest.setMethod(MethodType.POST);
            // 临时Token的会话名称，自己指定用于标识你的用户，主要用于区分Token颁发给谁
            assumeRoleRequest.setRoleSessionName(request.getRoleSessionName());

            // 赋予临时授权指定角色
            assumeRoleRequest.setRoleArn(RoleArn);
            if (request.getPolicy() == null || "".equals(request.getPolicy())) {
                assumeRoleRequest.setPolicy(policy);
            } else {
                assumeRoleRequest.setPolicy(request.getPolicy());
            }

            assumeRoleRequest.setDurationSeconds(outTime);
            // 发起请求，并得到response
            final com.aliyuncs.auth.sts.AssumeRoleResponse response = client.getAcsResponse(assumeRoleRequest);
            logger.info("临时授权返回数据："+ JSONObject.toJSON(response.getCredentials()));

            data.setExpiration(response.getCredentials().getExpiration());
            data.setAccessKeyId(response.getCredentials().getAccessKeyId());
            data.setAccessKeySecret(response.getCredentials().getAccessKeySecret());
            data.setSecurityToken(response.getCredentials().getSecurityToken());
            data.setRequestId(response.getRequestId());
            data.setUrl(OSS_END_POINT);
            if (request.getBucket() == null || "".equals(request.getBucket())) {
                data.setBucketName(bucket);
            } else {
                data.setBucketName(request.getBucket());
            }

            res.setCode("00");
            res.setMsg("临时授权申请成功");
            res.setData(data);
        } catch (ClientException e) {
            logger.error("生成临时授权异常：" + e);
            res.setCode("01");
            res.setMsg("生成临时授权失败");
            return res;
        }
        return res;
    }

    /**
     * 创建Bucket
     * @param request.bucket 名称 | request.policy 权限  Private-私有 PublicRead-公共读取 PublicReadWrite-公共读写
     * @return code 00成功 msg 描述
     * @date 2018-11-22 10:09:35
     */
    public BaseResponse<BucketInfo> addBucket(CommonParam commonParam, AuthOssStsRequest request) {
        BaseResponse res = new BaseResponse();

        String bucket = null;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {
            if (request.getBucket() == null || "".equals(request.getBucket())) {
                res.setCode("01");
                res.setMsg("Bucket不能为空");
                return res;
            }
            bucket = request.getBucket();

            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.判断Bucket是否存在
            if (ossClient.doesBucketExist(bucket)) {
                res.setCode("01");
                res.setMsg("已存在的Bucket");
                return res;
            }
            // 3.创建Bucket
            ossClient.createBucket(bucket);

            // 4.设置权限；默认私有 Private
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
            createBucketRequest.setCannedACL(CannedAccessControlList.Private);
            if (request.getPolicy() != null && !"".equals(request.getPolicy())) {
                switch (request.getPolicy()) {
                    case "Private":
                        createBucketRequest.setCannedACL(CannedAccessControlList.Private);
                        break;
                    case "PublicRead":
                        createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                        break;
                    case "PublicReadWrite":
                        createBucketRequest.setCannedACL(CannedAccessControlList.PublicReadWrite);
                        break;
                }
            }

            BucketInfo info = ossClient.getBucketInfo(bucket);

            res.setCode("00");
            res.setMsg("创建成功");
            res.setData(info);

            // 5.关闭连接
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("创建Bucket异常：" + e);
            res.setCode("01");
            res.setMsg("创建Bucket失败");
            return res;
        }
        return res;
    }

    /**
     * 创建Bucket
     * @param request.bucket 名称
     * @return code 00成功 msg 描述
     * @date 2018-11-22 11:42:35
     */
    public BaseResponse<String> delBucket(CommonParam commonParam, AuthOssStsRequest request) {
        BaseResponse res = new BaseResponse();

        String bucket = null;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;

        try {
            if (request.getBucket() == null || "".equals(request.getBucket())) {
                res.setCode("01");
                res.setMsg("Bucket不能为空");
                return res;
            }

            bucket = request.getBucket();

            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.判断空间是否存在
            if (!ossClient.doesBucketExist(bucket)) {
                res.setCode("01");
                res.setMsg("Bucket不存在");
                return res;
            }

            // 3.删除存储空间。
            ossClient.deleteBucket(bucket);

            res.setCode("00");
            res.setMsg("删除成功");

            // 4.关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("删除Bucket异常：" + e);
            res.setCode("01");
            res.setMsg("删除Bucket失败");
            return res;
        }
        return res;
    }

    /**
     * 获取Bucket列表
     * @param
     * @return code 00成功 msg 描述 data.list
     * @date 2018-11-22 13:15:35
     */
    public BaseResponse<GetBucketByListResponse> getBucketByList(CommonParam commonParam, AuthOssStsRequest request) {
        BaseResponse res = new BaseResponse();
        GetBucketByListResponse data = new GetBucketByListResponse();

        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {

            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.列举存储空间。
            List<Bucket> buckets = ossClient.listBuckets();

            data.setList(buckets);
            res.setCode("00");
            res.setMsg("查询成功");
            res.setData(data);

            // 3.关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("查询Bucket异常：" + e);
            res.setCode("01");
            res.setMsg("查询失败");
            return res;
        }
        return res;
    }

    /**
     * 文件上传
     * @param
     * @return code 00成功 msg 描述 data.list
     * @date 2018-11-22 15:44:35
     */
    public BaseResponse<String> putFile(CommonParam commonParam, PutFileRequest request) {
        BaseResponse res = new BaseResponse();
        String fileName = "";
        Object fileObject = "";

        String bucket = OSS_BUCKET_NAME;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {
            if (request.getType() == null || "".equals(request.getType())) {
                res.setCode("01");
                res.setMsg("上传方式不能为空");
                return res;
            }
            if (request.getFileName() == null || "".equals(request.getFileName())) {
                res.setCode("01");
                res.setMsg("文件名不能为空");
                return res;
            }
            fileName = request.getFileName();
            fileObject = request.getInputStream();

            if (request.getBucket() != null && !"".equals(request.getBucket())) {
                bucket = request.getBucket();
            }
            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.选择上传文件的方式
            // 3.上传文件
            switch (request.getType()) {
                case "STRING":
                    request.setType("BYTE");
                    fileObject = String.valueOf(fileObject).getBytes();
                case "BYTE":
                    ossClient.putObject(bucket, fileName, new ByteArrayInputStream((byte[]) fileObject));
                    break;
                case "INPUTURL":
                    InputStream inputStream = new URL(String.valueOf(fileObject)).openStream();
                    ossClient.putObject(bucket,fileName,inputStream);
                    break;
                case "INPUTFILE":
                    ossClient.putObject(bucket,fileName,(FileInputStream) request.getInputStream());
                    break;
                case "FILEPATH":
                    ossClient.putObject(bucket,fileName,(File) request.getInputStream());
                    break;
                default:
                    res.setCode("01");
                    res.setMsg("不支持该方式上传");
                    return res;
            }

            // 4.设置文件的访问权限。
            ossClient.setObjectAcl(bucket, fileName, CannedAccessControlList.Private);
            if (request.getPolicy() != null && !"".equals(request.getPolicy())) {
                switch (request.getPolicy()) {
                    case "Private":
                        ossClient.setObjectAcl(bucket, fileName, CannedAccessControlList.Private);
                        break;
                    case "PublicRead":
                        ossClient.setObjectAcl(bucket, fileName, CannedAccessControlList.PublicRead);
                        break;
                    case "PublicReadWrite":
                        ossClient.setObjectAcl(bucket, fileName, CannedAccessControlList.PublicReadWrite);
                        break;
                }
            }

            res.setCode("00");
            res.setMsg("上传成功");

            // 4.关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("上传异常：" + e);
            res.setCode("01");
            res.setMsg("上传失败");
            return res;
        }
        return res;
    }

    /**
     * 增加上传回调
     *
     * @date 2019-01-22 14:06:00
     */
    public BaseResponse putFileCallBack(CommonParam commonParam, PutFileRequest request) {
        BaseResponse res = new BaseResponse();
        String fileName = "";
        Object fileObject = "";

//        String bucket = OSS_BUCKET_NAME;
//        String endpoint=OSS_END_POINT;
//        String accessKeyId=OSS_ACCESS_KEY_ID;
//        String accessKeySecret=OSS_ACCESS_KEY_SECRET;

        String bucket = "roadoor-test-scjr";
        String endpoint="http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId="STS.NJpMFGgP8VmsraoxK49nHhJCr";
        String secretAccessKey="HzFxm5r5wt22XTjsWHaHLKFQmqqF8nhuYaJ9c1xRFCZ2";
        String accessKeySecret="CAISjAN1q6Ft5B2yfSjIr4nFBvzzio8Z4a+YcEfenEthNeFkh4/okDz2IHtEfXRsB+EXtfwynGxW5v0clqd0VoNeREDJVsZq8JVc/Fshr1FATInng4YfgbiJREI5YnyShb0GCoeUZdfZfejXHDKgvyRvwLz8WCy/Vli+S/OggoJmadJlMWvVaiFdVpUs32IAzvUXLnzML/2gHwf3i27LdipStxF7lHl05NaioNaV4QGMi0bhmK1H5dbrJZGoaM52eYtySMvwx+d0bO3GzTJL6hRHs5cs1PUVoW2d5IvGXgUPvknbbbGT2fRVAC5VI4oHIJID9qClxKUk4ryUxo2rlxwVbLsFWinSSNCtnsLOR7mkbIdmLLvxYSTA2NrJNIH6kXt9PS9Ga1IUK4txdyAuWUN8cFyAdP/7omKtSxy4Vq2I3Jsx1ZdI1Fjy9bKIXQPUE+zEjXhJa8RkMht0aU5Ng3avabMdNhZLel9gAKzQUYhocFVFoqHy+ArJTWhpxXpapOa7eOnXpq0P7x4TvlivcuAagAGars8HVSTt5RaeEN0i+tGnIMc96fESGtGvcIJ0o5bEUSrbQAlfPUccYmgfQmNYhXsXvoCQoZRMTSRrMM8AcTx+BhuSqltuqeY3meN0iNG1v7D0OCl/ZOXI6+H5LNzYZTpD8cB/0cYY0L8i4xM/S6PBS4LZ8KbGs+j9Snye9G2UUg==";

        // 您的回调服务器地址，如http://oss-demo.aliyuncs.com:23450或http://127.0.0.1:9090。
        String callbackUrl = "https://asseti-f04.shengcaijinrong.com/asset/callback/aliyun/oss";

        try {

            fileName = request.getFileName();
            fileObject = request.getInputStream();

            // 创建OSSClient实例。
            //OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, secretAccessKey, accessKeySecret);

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName,(File) fileObject);

            // 上传回调参数。
            Callback callback = new Callback();
            callback.setCallbackUrl(callbackUrl);
            // 设置回调请求消息头中Host的值，如oss-cn-hangzhou.aliyuncs.com。
            //callback.setCallbackHost("oss-cn-hangzhou.aliyuncs.com");
            // 设置发起回调时请求body的值。
            callback.setCallbackBody("{\\\"data\\\":{\\\"fileName\\\":\\\"963e21a4cbb9a51d16bd1958345917cb.jpg\\\",\\\"orderId\\\":\\\"28d1cffd5ba249f6a697c3ea6388db0a\\\",\\\"path\\\":\\\"outside/X201902222354654563/CARDID-JUST/20190408\\\",\\\"transNum\\\":\\\"d0ad789396564191ade5a1db9d2af797\\\",\\\"uploadType\\\":\\\"CARDID-JUST\\\",\\\"zaofId\\\":\\\"14\\\"},\\\"merchantNo\\\":\\\"X201902222354654563\\\",\\\"method\\\":\\\"test\\\",\\\"msgId\\\":\\\"ec4043e233494310ab54ba28c35db801\\\",\\\"source\\\":\\\"ossCallback\\\",\\\"version\\\":\\\"1.0.0.0\\\"}");
            // 设置发起回调请求的Content-Type。
            callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);
            // 设置发起回调请求的自定义参数，由Key和Value组成，Key必须以x:开始。
            callback.addCallbackVar("x:argv", "{\\\"data\\\":{\\\"fileName\\\":\\\"963e21a4cbb9a51d16bd1958345917cb.jpg\\\",\\\"orderId\\\":\\\"28d1cffd5ba249f6a697c3ea6388db0a\\\",\\\"path\\\":\\\"outside/X201902222354654563/CARDID-JUST/20190408\\\",\\\"transNum\\\":\\\"d0ad789396564191ade5a1db9d2af797\\\",\\\"uploadType\\\":\\\"CARDID-JUST\\\",\\\"zaofId\\\":\\\"14\\\"},\\\"merchantNo\\\":\\\"X201902222354654563\\\",\\\"method\\\":\\\"test\\\",\\\"msgId\\\":\\\"ec4043e233494310ab54ba28c35db801\\\",\\\"source\\\":\\\"ossCallback\\\",\\\"version\\\":\\\"1.0.0.0\\\"}");
            putObjectRequest.setCallback(callback);

            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

            // 读取上传回调返回的消息内容。
            byte[] buffer = new byte[1024];
            putObjectResult.getCallbackResponseBody().read(buffer);
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            putObjectResult.getCallbackResponseBody().close();

            // 关闭OSSClient。
            ossClient.shutdown();
            res.setCode("00");
            res.setMsg("成功");
        } catch (Exception e) {
            logger.error("上传异常：" + e);
            res.setCode("01");
            res.setMsg("上传失败");
        }
        return res;
    }

    /**
     * 生成临时访问授权
     * @param   fileName 文件名
     * @return code 00成功 msg 描述 data.list
     * @date 2018-11-22 15:58:35
     */
    public BaseResponse<AuthOssStsResponse> newOssUrl(CommonParam commonParam, PutFileRequest request) {
        BaseResponse res = new BaseResponse();
        AuthOssStsResponse data = new AuthOssStsResponse();

        Integer outTime = OSS_OUT_TIME;
        String bucket = OSS_BUCKET_NAME;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {
            if (request.getFileName() == null || "".equals(request.getFileName())) {
                res.setCode("01");
                res.setMsg("文件名不能为空");
                return res;
            }

            if (request.getBucket() != null && !"".equals(request.getBucket())) {
                bucket = request.getBucket();
            }

            // 1.创建连接
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(20 * 1000); // 连接超时，默认15秒
            conf.setSocketTimeout(20 * 1000); // socket超时，默认15秒
            conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
            OSSClient ossClient=new OSSClient(endpoint, accessKeyId, accessKeySecret,conf);

            // 2.设置超时时间
            Date expiration = new Date(new Date().getTime() + outTime * 1000);

            // 3.判断文件是否存在
            if (ossClient.doesObjectExist(bucket,request.getFileName())) {
                res.setCode("01");
                res.setMsg("文件不存在");
                // return res;      // 安全起见，不进行验证
            }

            // 4.生成授权
            URL url = ossClient.generatePresignedUrl(bucket, request.getFileName(), expiration);

            data.setUrl(url.toString());
            res.setCode("00");
            res.setMsg("申请成功");
            res.setData(data);

            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("申请临时授权访问异常：" + e);
            res.setCode("01");
            res.setMsg("申请失败");
            return res;
        }
        return res;
    }

    /**
     * 设置防盗链
     * @param   list 白名单列表
     * @return code 00成功 msg 描述 data.list
     * @date 2018-11-22 15:58:35
     */
    public BaseResponse<String> setBucketReferer(CommonParam commonParam, RefererRequest request) {
        BaseResponse res = new BaseResponse();

        String bucket = OSS_BUCKET_NAME;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {
            if (request.getRefererList().size() == 0) {
                res.setCode("01");
                res.setMsg("至少需要声明一个地址");
                return res;
            }
            if (request.getBucket() != null && !"".equals(request.getBucket())) {
                bucket = request.getBucket();
            }

            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.设置存储空间Referer列表。设为true表示Referer字段允许为空。
            BucketReferer br = new BucketReferer(request.isReferer(), request.getRefererList());
            ossClient.setBucketReferer(bucket, br);

            res.setCode("00");
            res.setMsg("设置成功");

            // 3.关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("设置防盗链异常：" + e);
            res.setCode("01");
            res.setMsg("设置防盗链失败");
            return res;
        }
        return res;
    }

    public BaseResponse<RefererResPonse> getBucketReferer(CommonParam commonParam, RefererRequest request) {
        BaseResponse res = new BaseResponse();
        RefererResPonse data = new RefererResPonse();

        String bucket = OSS_BUCKET_NAME;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {
            if (request.getBucket() != null && !"".equals(request.getBucket())) {
                bucket = request.getBucket();
            }

            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.获取存储空间Referer白名单列表。
            BucketReferer br = ossClient.getBucketReferer(bucket);

            data.setList(br.getRefererList());
            res.setCode("00");
            res.setMsg("查询成功");
            res.setData(data);

            // 3.关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("查询防盗链列表异常：" + e);
            res.setCode("01");
            res.setMsg("查询防盗链列表失败");
            return res;
        }
        return res;
    }

    public BaseResponse<String> delBucketReferer(CommonParam commonParam, RefererRequest request) {
        BaseResponse res = new BaseResponse();

        String bucket = OSS_BUCKET_NAME;
        String endpoint=OSS_END_POINT;
        String accessKeyId=OSS_ACCESS_KEY_ID;
        String accessKeySecret=OSS_ACCESS_KEY_SECRET;
        try {
            if (request.getBucket() != null && !"".equals(request.getBucket())) {
                bucket = request.getBucket();
            }

            // 1.创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            // 2.防盗链不能直接清空，需要新建一个允许空Referer的规则来覆盖之前的规则。
            BucketReferer br = new BucketReferer();
            ossClient.setBucketReferer(bucket, br);

            res.setCode("00");
            res.setMsg("清除成功");

            // 3.关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            logger.error("清除防盗链异常：" + e);
            res.setCode("01");
            res.setMsg("清除失败");
            return res;
        }
        return res;
    }
}
